package com.zl.learning.io.nio;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketAddress;
import java.nio.charset.StandardCharsets;

public class UDPServer {
    public static void main(String[] args) {
        byte[] buf = new byte[1024];
        new Thread(()->{
            try (DatagramSocket ds = new DatagramSocket(9999)){
                System.out.println("UDP server start at:"+9999);
                while (ds!=null){
                    DatagramPacket dp = getDatagramPacket(buf);
                    ds.receive(dp);
                    System.out.println(new String(dp.getData(), StandardCharsets.UTF_8));
                    DatagramPacket dp2 = getDatagramPacket("我已收到".getBytes(),dp.getSocketAddress());
                    ds.send(dp2);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

    private static DatagramPacket getDatagramPacket(byte[] buf) {
        return new DatagramPacket(buf,buf.length);
    }

    private static DatagramPacket getDatagramPacket(byte[] buf, SocketAddress address) {
        return new DatagramPacket(buf,buf.length,address);
    }
}
